<?php

class WxMessageModule
{
    public function orderstatus() {
        global $_FANWE;
        $id = $_GET['id'];
        if(!is_numeric($id)) ajax_msg(1);
        $order = FDB::fetchFirst("SELECT * FROM ml_wogu_order WHERE orderid={$id}");
        if($order) {
            if($_GET['paystep'] == 0 && in_array($order['flag'], array(3, 4))) {
                ajax_msg(0);
            } elseif($_GET['paystep'] == 1 && $order['flag'] == 4) {
                ajax_msg(0);
            }
        }

        ajax_msg(1);
    }

    public function check() {
        global $_FANWE;

        // 订单检测
        $return = array();
        if($_FANWE['user']['user_type'] == 1) {
            $order = FDB::fetchFirst("SELECT id,total_fee,ordername,userid FROM ml_wogu_order WHERE shopid={$_FANWE['uid']} AND flag=0 AND is_notify=0 ORDER BY id DESC LIMIT 0,1");
            if(!empty($order)) {
                FDB::update('wogu_order', array('is_notify' => 1), array('id' => $order['id']));
                $buyer = FDB::fetchFirst("SELECT * FROM ml_user WHERE uid={$order['userid']}");
                $order['buyer'] = $buyer['user_name'];
                $return['order1'] = $order;
            } else {
                $order3 = FDB::fetchFirst("SELECT id,total_fee,ordername,userid FROM ml_wogu_order WHERE shopid={$_FANWE['uid']} AND flag=2 AND is_notify=2 ORDER BY id DESC LIMIT 0,1");
                if(!empty($order3)) {
                    FDB::update('wogu_order', array('is_notify' => 3), array('id' => $order3['id']));
                    $return['order3'] = array(
                        'orderid' => $order3['id'],
                        'paystep' => 0,
                        'qrcode' => "http://{$_SERVER['HTTP_HOST']}/misc.php?ajax&action=qrcode&orderid={$order3['id']}&t=".time(),
                    );
                }
            }
        } else {
            $order = FDB::fetchFirst("SELECT id,total_fee,ordername,userid FROM ml_wogu_order WHERE userid={$_FANWE['uid']} AND flag=1 AND is_notify=1 ORDER BY id DESC LIMIT 0,1");
            if(!empty($order)) {
                FDB::update('wogu_order', array('is_notify' => 2), array('id' => $order['id']));
                $sql = 'SELECT * FROM '.FDB::table('wogu_order_contract').' WHERE order_id='.$order['id'];
                $contract = FDB::fetchFirst($sql);
                $contract['imgs'] = unserialize($contract['imgs']);
                $order['contract'] = $contract;
                $return['order2'] = $order;
            }
        }

        // 微信检测
        $res = FDB::query("SELECT wwr.*,u.user_name,u.avatar FROM ml_wogu_wxmessage_recent wwr INNER JOIN ml_user u ON wwr.uid=u.uid WHERE wwr.to_uid={$_FANWE['uid']} AND is_notify=0 ORDER BY wwr.dateline DESC");
        $newmsgs = $uids = array();
        while($data = FDB::fetch($res)) {
            $data['avatar'] = avatar($data['avatar'], 'm');
            $data['dateline_show'] = date('Y-m-d H:i:s', $data['dateline']);
            $data['hisuid'] = $data['uid'];
            $uids[] = $data['uid'];
            $newmsgs[$data['uid']] = $data;
        }

        $res = FDB::query("SELECT sum(msg_num) as msg_num FROM ml_wogu_wxmessage_recent WHERE to_uid={$_FANWE['uid']}");
        $r = FDB::fetch($res);
        $return['msg_num'] = $r['msg_num'];
        if(empty($newmsgs)) ajax_msg(1, $return);
        FDB::query("UPDATE ml_wogu_wxmessage_recent SET is_notify=1 WHERE to_uid={$_FANWE['uid']} AND uid IN(".implode(',', $uids).")");

        $return['items'] = array_values($newmsgs);
        $return['msg_num'] = $r['msg_num'];
        ajax_msg(0, $return);
    }

    public function send() {
        global $_FANWE;

        $uid = intval($_GET['uid']);
        if($uid <= 0) exit('0');
        $message = htmlspecialchars(trim($_POST['message']));
        if(empty($message)) exit('0');

        $endsj = time() - 300;
        $lastmsg = FDB::fetchFirst("SELECT * FROM ml_wogu_wxmessage_logs WHERE ((uid={$_FANWE['uid']} AND to_uid={$uid}) OR (uid={$uid} AND to_uid={$_FANWE['uid']})) AND dateline>{$endsj}");
        if(!empty($lastmsg)) {
            $dateline = '';
        } else {
            $dateline = date('H:i');
        }

        $id = FDB::insert('wogu_wxmessage_logs', array(
            'uid' => $_FANWE['uid'],
            'to_uid' => $uid,
            'message' => $message,
            'dateline' => time()
        ), true);
        if(!$id) exit('0');
        FDB::query("UPDATE ml_user SET wxmessage_num=wxmessage_num+1 WHERE uid={$uid}");
        $sql = 'SELECT * FROM '.FDB::table('wogu_wxmessage_recent')." WHERE uid={$_FANWE['uid']} AND to_uid={$uid}";
        $r = FDB::fetchFirst($sql);
        if(empty($r)) {
            FDB::insert('wogu_wxmessage_recent', array(
                'uid' => $_FANWE['uid'],
                'to_uid' => $uid,
                'dateline' => time(),
                'msg_num' => 1,
                'is_notify' => 0,
                'last_msg' => $message,
            ));
        } else {
            FDB::query("UPDATE ml_wogu_wxmessage_recent SET last_msg='{$message}',msg_num=msg_num+1,is_notify=0,dateline=".time()." WHERE uid={$_FANWE['uid']} AND to_uid={$uid}");
        }

        if(isset($_GET['ajax'])) {
            ajax_msg(0, array(
                'lastid' => $id,
                'msg' => array(
                    'ismesend' => true,
                    'avatar' => avatar($_FANWE['user']['avatar'], 'm'),
                    'message' => $message,
                    'dateline' => $dateline
                )
            ));
        } else {
            exit('1#'.$id);
        }
    }

    public function logs() {
        global $_FANWE;

        if(empty($_FANWE['uid'])) exit;

        $uid = intval($_GET['uid']);
        if(!$uid) exit;
        $msgid = intval($_GET['msgid']);
        $he = FS('User')->getUserById($uid);
        $me = FS('User')->getUserById($_FANWE['uid']);
        // 如果是初次聊天
        $res = FDB::query("SELECT COUNT(*) AS num FROM ml_wogu_wxmessage_logs WHERE ((uid={$_FANWE['uid']} AND to_uid={$uid}) OR (uid={$uid} AND to_uid={$_FANWE['uid']}))");
        $r = FDB::fetch($res);
        if($r['num'] == 0) {
            // 初始化wogu_wxmessage_recent表
            $lastmessage = '亲，有什么感兴趣的吗？';
            $sql = 'SELECT * FROM '.FDB::table('wogu_wxmessage_recent')." WHERE uid={$uid} AND to_uid={$_FANWE['uid']}";
            $r = FDB::fetchFirst($sql);
            if(empty($r)) {
                FDB::insert('wogu_wxmessage_recent', array(
                    'uid' => $uid,
                    'to_uid' => $_FANWE['uid'],
                    'dateline' => time(),
                    'msg_num' => 1,
                    'is_notify' => 0,
                    'last_msg' => $lastmessage,
                ));
            }

            // 初始化wogu_wxmessage_logs表
            FDB::insert('wogu_wxmessage_logs', array(
                'uid' => $uid,
                'to_uid' => $_FANWE['uid'],
                'message' => $lastmessage,
                'dateline' => time()
            ));

            $ftime = date('H:i');
        }

        $pretime = $preftime = '';
        if($msgid > 0) {
            $sql = 'SELECT * FROM '.FDB::table('wogu_wxmessage_logs')." WHERE id={$msgid}";
            $last_msg = FDB::fetchFirst($sql);
            get_firendly_time($last_msg['dateline'], $currtime, $pretime, $preftime);
        }

        $res = FDB::query("SELECT * FROM ml_wogu_wxmessage_logs WHERE id>{$msgid} AND ((uid={$_FANWE['uid']} AND to_uid={$uid}) OR (uid={$uid} AND to_uid={$_FANWE['uid']}))");
        $messages = array();
        $currtime = time();
        while($data = FDB::fetch($res)) {
            $data['ismesend'] = $data['uid'] == $_FANWE['uid'];
            $data['to_avatar'] = avatar($he['avatar'], 'm');
            $data['avatar'] = avatar($me['avatar'], 'm');
            $data['dateline'] = get_firendly_time($data['dateline'], $currtime, $pretime, $preftime);
            $messages[] = $data;
        }

        FDB::query("UPDATE ml_wogu_wxmessage_recent SET msg_num=0 WHERE uid={$uid} AND to_uid={$_FANWE['uid']}");
        ajax_msg(0, $messages);
    }

    public function index() {
        global $_FANWE;

        $uid = intval($_GET['uid']);
        $uname = htmlspecialchars($_GET['uname']);

        $user_list = array();
        $res = FDB::query('SELECT u.uid,u.user_name,u.avatar
                FROM '.FDB::table('user_follow').' AS uf
                INNER JOIN '.FDB::table('user').' AS u ON u.uid = uf.uid
                WHERE uf.f_uid = '.$_FANWE['uid'].' ORDER BY uf.create_time DESC');
        while($data = FDB::fetch($res)) {
            $data['avatar'] = avatar($data['avatar'], 'm');
            $user_list[] = $data;
        }

        $recents = array();
        $res = FDB::query('SELECT * FROM '.FDB::table('wogu_wxmessage_recent').' WHERE uid = '.$_FANWE['uid'].' OR to_uid='.$_FANWE['uid'].' ORDER BY dateline DESC');
        $unnotifyids = array();
        while($v = FDB::fetch($res)) {
            $hisuid = $v['uid'] == $_FANWE['uid'] ? $v['to_uid'] : $v['uid'];
            if(!isset($recents[$hisuid])) {
                $recents[$hisuid] = $v;
            }

            if($v['to_uid'] == $_FANWE['uid'] && $v['is_notify'] == 0) {
                $unnotifyids[] = $v['uid'];
            }
        }
        if(!empty($recents)) {
            $uids = array_keys($recents);
            $res = FDB::query('SELECT * FROM '.FDB::table('user').' WHERE uid IN('.implode(',', $uids).')');
            while($v = FDB::fetch($res)) {
                $recents[$v['uid']]['user_name'] = $v['user_name'];
                $recents[$v['uid']]['avatar'] = avatar($v['avatar'], 'm');
            }

            if(!empty($unnotifyids)) {
                FDB::query("UPDATE ml_wogu_wxmessage_recent SET is_notify=1 WHERE to_uid={$_FANWE['uid']} AND uid IN(".implode(',', $unnotifyids).")");
            }
        }

        include template('page/wxmessage/index');
        display();
        exit;
    }

    public function app_recent() {
        global $_FANWE;

        $recents = array();
        $res = FDB::query('SELECT * FROM '.FDB::table('wogu_wxmessage_recent').' WHERE uid = '.$_FANWE['uid'].' OR to_uid='.$_FANWE['uid'].' ORDER BY dateline DESC');
        $unnotifyids = array();
        while($v = FDB::fetch($res)) {
            $hisuid = $v['uid'] == $_FANWE['uid'] ? $v['to_uid'] : $v['uid'];
            if(!isset($recents[$hisuid])) {
                $v['hisuid'] = $hisuid;
                $v['dateline_show'] = date('Y/m/d H:i:s', $v['dateline']);
                $recents[$hisuid] = $v;
            }

            if($v['to_uid'] == $_FANWE['uid'] && $v['is_notify'] == 0) {
                $unnotifyids[] = $v['uid'];
            }
        }
        if(!empty($recents)) {
            $uids = array_keys($recents);
            $res = FDB::query('SELECT * FROM '.FDB::table('user').' WHERE uid IN('.implode(',', $uids).')');
            while($v = FDB::fetch($res)) {
                $recents[$v['uid']]['user_name'] = $v['user_name'];
                $recents[$v['uid']]['avatar'] = avatar($v['avatar'], 'm');
            }

            if(!empty($unnotifyids)) {
                FDB::query("UPDATE ml_wogu_wxmessage_recent SET is_notify=1 WHERE to_uid={$_FANWE['uid']} AND uid IN(".implode(',', $unnotifyids).")");
            }
        }

        ajax_msg(0, array_values($recents));
    }
}

function get_firendly_time($dateline, $currtime, &$pretime, &$preftime) {
    $subtime = $currtime - $dateline;
    $subday = (strtotime(date('Y-m-d', $currtime)) - strtotime(date('Y-m-d', $dateline))) / (24*3600);
    if($subday > 7) {
        $ftime = date('Y年m月d日', $dateline);
    } elseif($subday > 0) {
        $ftime = get_han_num(date('w', $dateline));
    } else {
        if($preftime == '') {
            $ftime = date('H:i', $dateline);
        } else {
            if($dateline - $pretime < 120) {
                $ftime = $preftime;
            } else {
                $ftime = date('H:i', $dateline);
            }
        }
    }

    if($preftime == '' || $preftime != $ftime) {
        $pretime = $dateline;
        return $preftime = $ftime;
    }

    return '';
}

function get_han_num($w) {
    $map = array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
    return $map[$w];
}

function ajax_msg($error, $data = '') {
    $arr = array(
        'error' => $error,
    );

    if($data) {
        $arr['data'] = $data;
    }

    exit(json_encode($arr));
}